package com.example.zqq.mysnake.Http;

import android.content.Context;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.google.gson.Gson;

/**
 * Js调用Android方法 on 2017/9/20.
 * 被JS调用的方法必须加入@JavascriptInterface注解
 */

public class JSToAndroidUtils extends Object {

    private Context context;
    private WebView webView;

    public JSToAndroidUtils(Context context, WebView webView) {
        this.context = context;
        this.webView = webView;
    }

    @JavascriptInterface
    public void goRegister(String info) {
        Log.e("Tag-regist", "rrrrrrr=" + info);
        APIService.getInstance().test(new ProgressSubscriber<Object>(true) {
            @Override
            public void onNext(Object o) {
//                Log.e("Tag-jstoandroid:", String.valueOf(o));
            }
        });
    }

    @JavascriptInterface
    public String back() {
        String s = "66666";
        return s;
    }


    @JavascriptInterface
    public void requestData(String string) {
        Log.e("Tag-request:", "request");
//        Log.e("Tag-jstoA-requestData", "jjjjjjjjjjjjjj=" + string);

//        String str = "{\"url\":\"www.baidu.com\",\"body\":{name:\"zqq\",page:\"12\",age:\"22\"}}";
//        TestMap map1 = new Gson().fromJson(str, TestMap.class);
//        Log.e("Tag-map=", map1.url);
//        HashMap<String, Object> map =  map1.map;
//        Log.e("Tag-map22=", map.get("name").toString());

        final ApiItem apiItem = new Gson().fromJson(string, ApiItem.class);
        APIService.getInstance().uncertainAPI(apiItem, new ProgressSubscriber<Object>(true) {
            @Override
            public void onNext(Object o) {
                String data = new Gson().toJson(o);
                String jsUrl = apiItem.getDone() + "(" + data + ")";
                webView.loadUrl("javascript:" + jsUrl);                                   //第一种方法
//                WebViewManage.setAndroidToJs(context, webView, jsUrl);                    //第二种方法
//                AndroidToJSUtils.setJsLoadUrl(webView, jsUrl);                              //第三种方法
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                String data = e.getMessage();
                String jsurl = apiItem.getFail() + "(" + data + ")";
                webView.loadUrl("javascript:" + jsurl);                                   //第一种方法

//                AndroidToJSUtils.setJsLoadUrl(webView, jsurl);
            }
        });
    }

}
